package com.pzy.controller;

import com.github.pagehelper.PageInfo;
import com.pzy.controller.results.Results;
import com.pzy.domain.User;
import com.pzy.service.UserService;
import com.pzy.system.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public Results addUser(User user){
        boolean flag = userService.addUser(user);
        return new Results(flag?Code.SAVE_OK:Code.SAVE_FAIL);
    }

    @DeleteMapping("/{userID}")
    public Results deleteUser(@PathVariable Integer userID){
        boolean flag = userService.deleteUser(userID);
        return new Results(flag?Code.DELETE_OK:Code.DELETE_FAIL);
    }
    @PutMapping
    public Results updateUser(User user){
        boolean flag = userService.updateUser(user);
        return new Results(flag?Code.UPDATE_OK:Code.UPDATE_FAIL);
    }
    @GetMapping("/{userID}")
    public Results getOne(@PathVariable Integer userID){
        User one = userService.getOne(userID);
       if(userID==1) {throw new BusinessException("查询出错啦",Code.SELECT_FAIL);};
        return new Results(one != null?Code.SELECT_OK:Code.SELECT_FAIL,one);
    }
    @GetMapping("/{page}/{size}")
    public Results getAll(@PathVariable  int page,@PathVariable  int size){
        PageInfo<User> all = userService.getAll(page, size);
        return new Results(all != null?Code.SELECT_OK:Code.SELECT_FAIL,all);
    }
    @PostMapping("/login")
    public Results getUser(String userName, String password){
        User user = userService.getUser(userName, password);
        return new Results(user != null?Code.SELECT_OK:Code.SELECT_FAIL,user);
    }
}
